﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public delegate void TickHandler(double Time, int i );
   
    public partial class Form1 : Form
    {
       
        public Form1()
        {
            InitializeComponent();
            
        }

        public void OnTickHandler(double Time, int i) 
        {
            label1.Text = Convert.ToString(Convert.ToInt32(Time));
            label2.Text = Convert.ToString(i);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Interpolator ob = new Interpolator(Convert.ToDouble(textBox1.Text), Convert.ToDouble(textBox2.Text), Convert.ToDouble(textBox3.Text));
            ob.TH += new TickHandler(OnTickHandler);        
            ob.Start();
    //        label1.Text = Convert.ToString(Interpolator.test);
             

        }
    }

    class MyTimer : Timer
    {
        public static int iii = 0;

        protected override void OnTick(EventArgs e)
        {
            base.OnTick(e);
            iii = iii + 1;
        }
    }


    class Interpolator
    {
   //     private TickHandler TH;
        private TimeSpan TLeft;
        private DateTime StartTime, NowTime;
        private double iFrst, iScnd, iTime;
        public static double test;
        private double weight;
        public System.Windows.Forms.Timer aTimer;
        private int delta;

        public event TickHandler TH;

        public Interpolator(double i, double x, double y)
        {
            iFrst = i;
            iScnd = x;
            iTime = y;
            test = 0;
            delta = Convert.ToInt32(Math.Abs(iFrst-iScnd));
        //    TH = new TickHandler
        }

        public void Start()
        {
            if (test >= iScnd) aTimer.Stop();
            aTimer = new MyTimer();
            aTimer.Interval = (10);
            StartTime = DateTime.Now;
            aTimer.Tick += new EventHandler(OnTick);
            aTimer.Start();
        }


        //public void Add_onTick(TickHandler deleg)
        //{
        //    TH += deleg;
        //}


        public void OnTick(object sender, EventArgs e)
        {

            if (delta <= test) aTimer.Stop();
            NowTime = DateTime.Now;
            TLeft = NowTime - StartTime;
            weight = TLeft.TotalMilliseconds / Convert.ToDouble(iTime*1000);
            test = Calculate();
            TH(test,MyTimer.iii);
        }

        public double Calculate()
        {
            return (iFrst + (iScnd - iFrst) * weight);
        }
    }
}
